package com.lsw.view;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

import com.lsw.R;
import com.lsw.photo.IBanner;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;


/**
 * 广告
 *
 * @author heiyue heiyue623@126.com
 * @ClassName: BannerView
 * @Description:
 * @date 2014-10-27 下午1:07:31
 */
@SuppressLint("ClickableViewAccessibility")
public class BannerView extends RelativeLayout {
    // private Context context;

    public BannerView(Context context) {
        super(context);
        initViews(context);
    }

    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);
    }

    public BannerView(Context context, AttributeSet attrs, int in) {
        super(context, attrs, in);
        initViews(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    private void initViews(Context context) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.fragment_image_pager, this);
        pager = (ViewPager) view.findViewById(R.id.pager);
        pagerAdapter = new SamplePagerAdapter();
        pager.setAdapter(pagerAdapter);
        indicator = (CirclePageIndicator) view
                .findViewById(R.id.indicator);

        handler = new Handler();
        handler.postDelayed(runnable, AUTO_SCROLL_TIME);
        indicator.setViewPager(pager);
    }

    public void setIndicatorColor(int colorFill, int colorPage,
                                  boolean isCenter, boolean isAlignLeft) {
        indicator.setFillColor(colorFill);
        indicator.setPageColor(colorPage);
        indicator.setCentered(isCenter, isAlignLeft);
        invalidate();
    }

    @Override
    protected void onDetachedFromWindow() {
        handler.removeCallbacks(runnable);
        super.onDetachedFromWindow();
    }

    /**
     * 广告图的自动滚动时间
     */
    public static final int AUTO_SCROLL_TIME = 1000 * 5;
    private ViewPager pager;
    private SamplePagerAdapter pagerAdapter;
    public CirclePageIndicator indicator;
    private Handler handler;

    /**
     * handler 通知banner 自动轮播图片
     */
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (pager != null) {
                PagerAdapter adapter = pager.getAdapter();
                if (adapter != null) {
                    int childCount = adapter.getCount();
                    int currentItem = pager.getCurrentItem();
                    if (childCount > 1) {
                        if (currentItem == childCount - 1) {
                            pager.setCurrentItem(0);
                        } else {
                            pager.setCurrentItem(currentItem + 1);
                        }
                        handler.postDelayed(runnable, AUTO_SCROLL_TIME);
                    }
                }
            }
        }
    };

    private List<? extends IBanner> imageList;

    public void setData(List<? extends IBanner> imagePaths) {
        handler.removeCallbacks(runnable);
        pagerAdapter.setData(imagePaths);
        imageList = imagePaths;
        if (imagePaths != null && imagePaths.size() > 1) {
            indicator.setVisibility(View.VISIBLE);
        } else {
            indicator.setVisibility(View.GONE);
        }
        handler.postDelayed(runnable, AUTO_SCROLL_TIME);
    }

    public List<? extends IBanner> getData() {
        return imageList;
    }

    /**
     * item的点击回调
     *
     * @param bannerItemClick
     */
    public void setOnItemClickListener(OnBannerItemClick bannerItemClick) {
        pagerAdapter.setOnItemClickListener(bannerItemClick);
    }

    /**
     * banner单项点击事件
     *
     * @author heiyue heiyue623@126.com
     * @ClassName: OnBannerItemClick
     * @Description:
     * @date 2014-6-30 下午1:47:20
     */
    public interface OnBannerItemClick {
        /**
         * 当前点击项
         *
         * @param item
         * @param position
         */
        void onItemClick(IBanner item, int position);
    }

    public void setDisplayImageOptions(DisplayImageOptions displayImageOptions) {
        if (null != pagerAdapter) {
            pagerAdapter.options = displayImageOptions;
        }
    }

    class SamplePagerAdapter extends PagerAdapter {
        private List<IBanner> images;
        private OnBannerItemClick bannerItemClick;
        private DisplayImageOptions options;

        public SamplePagerAdapter() {
            this.images = new ArrayList<IBanner>();
        }

        public void setOnItemClickListener(OnBannerItemClick bannerItemClick) {
            this.bannerItemClick = bannerItemClick;
        }

        public void setData(List<? extends IBanner> images) {
            this.images.clear();
            if (images != null) {
                this.images.addAll(images);
            }
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, final int position) {
            IBanner banner = this.images.get(position);
            ImageView photoView = new ImageView(container.getContext());
            // photoView.setImageResource(R.drawable.pub_select_bg);
            photoView.setScaleType(ScaleType.CENTER_CROP);
            photoView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (bannerItemClick != null) {
                        bannerItemClick.onItemClick(images.get(position),
                                position);
                    }
                }
            });
            if (options == null) {
                options = DisplayImageOptions.createSimple();
            }

            if (banner.getResource() > 0) {
                photoView.setImageResource(banner.getResource());
            } else if (banner.getImgBg() != null) {
                photoView.setImageBitmap(banner.getImgBg());
            } else if (banner.getUrl() != null) {
                ImageLoader.getInstance().displayImage(banner.getUrl(),
                        photoView, options);
            }

            container.addView(photoView, LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT);

            return photoView;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    public void setCurrentItem(int position) {
        if (null != indicator) {
            indicator.setCurrentItem(position);
        }
    }

    public void setOnPageChangeListener(
            OnPageChangeListener onPageChangeListener) {
        if (null != indicator) {
            indicator.setOnPageChangeListener(onPageChangeListener);
        }
    }

}
